package com.zlx.xBiaoShop.controller;

import com.alibaba.fastjson.JSONObject;
import com.zlx.xBiaoShop.entity.User;
import com.zlx.xBiaoShop.service.UserService;
import com.zlx.xBiaoShop.utils.HttpUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author 周罗校
 * @Description qq登陆
 * @ClassName QqLoginController
 * @date 2020.11.25 15:02:51
 * 该版权归周罗校所有，最终解释权以官方为准
 */
@RestController
public class QqLoginController {
    @Autowired
    private UserService userService;

    @Value("${qq.AppID}")
    private String appID;

    @Value("${qq.AppKey}")
    private String AppKey;

    @Value("${qq.redirect_uri}")
    private String redirectUri;

    @RequestMapping("/toQQLogin")
    public void toQQLogin(HttpServletResponse response) {
        String url = "https://graph.qq.com/oauth2.0/authorize?response_type=code" +  //response_type必选属性：属性值为code
                "&client_id=" + appID +
                "&redirect_uri=" + redirectUri +
                "&state=test";
        try {
            response.sendRedirect(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping("/qq_login")
    public void QQLogin(HttpServletRequest request, HttpServletResponse response) {
        try {
            HttpSession session = request.getSession();
            String code = request.getParameter("code");
            //如果成功返回，即可在返回包中获取到Access Token
            String url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code" +//必选，此值固定为“authorization_code”
                    "&client_id=" + appID +
                    "&client_secret=" + AppKey +
                    "&code=" + code +   //上一步返回的authorization code，url带着的参数
                    "&redirect_uri=" + redirectUri; //与上面一步中传入的redirect_uri保持一致。
            //模拟http请求，获取token
            String access_token = getAccessToken(url);
            //根据token获取openId
            url = "https://graph.qq.com/oauth2.0/me?access_token=" + access_token;
            String openID = getOpenID(url);
            //调用qq用户信息的json串api地址
            url = "https://graph.qq.com/user/get_user_info?access_token=" + access_token +
                    "&oauth_consumer_key=" + appID +
                    "&openid=" + openID;
            User user = new User();
            user.setQqOpenid(openID);
            user = (User) userService.selectUserByQqOpenId(openID);
            if (user == null) {
                //发送模拟的http请求，获取并返回qq用户信息的json串
                JSONObject userInfo = HttpUtils.getUserInfo(url);
                System.out.println(userInfo);
                user = new User();
                user.setPic(userInfo.getString("figureurl_qq"));
                user.setSex(userInfo.getString("gender_type"));
                user.setRealName("暂无验证");
                user.setUsername(userInfo.getString("nickname"));
                user.setQqOpenid(openID);
//                System.out.println(user);
                user.setPassword("123456");
//                user.setAge(0);
                user = userService.save(user);
            }
            session.setAttribute("loginUser", user);
            response.sendRedirect("/wxOrQqLogin.html");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private String getAccessToken(String url) throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();
        String token = null;

        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            if (result.indexOf("access_token") >= 0) {
                String[] array = result.split("&");
                for (String str : array) {
                    if (str.indexOf("access_token") >= 0) {
                        token = str.substring(str.indexOf("=") + 1);
                        break;
                    }
                }
            }
        }
        httpGet.releaseConnection();
        return token;
    }


    public static String getOpenID(String url) throws IOException {
        JSONObject jsonObject = null;
        CloseableHttpClient client = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet(url);
        HttpResponse response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            String result = EntityUtils.toString(entity, "UTF-8");
            jsonObject = parseJSONP(result);
        }
        httpGet.releaseConnection();
        if (jsonObject != null) {
            return jsonObject.getString("openid");
        } else {
            return null;
        }
    }

    private static JSONObject parseJSONP(String jsonp) {
        int startIndex = jsonp.indexOf("(");
        int endIndex = jsonp.lastIndexOf(")");
        String json = jsonp.substring(startIndex + 1, endIndex);
        return JSONObject.parseObject(json);
    }
}
